# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: leon

from coin.exchange.base.kr_rest.currency import NativeCurrency
from coin.exchange.base.kr_rest.currency_constants import (
    BCHABC_BCHSV_FORK_TIME,
    BCHA_BCHN_FORK_TIME)
from coin.exchange.bybit.kr_rest.constants import currency_list


def validate_native_currency(currency):
  assert type(currency) == str, str(currency)
  assert currency.upper() == currency
  assert currency in currency_list, currency


def to_native_currency(currency):
  if currency == 'BCHSV':
    native_currency = 'BSV'
  elif currency in ('BCHABC', 'BCHN'):
    native_currency = 'BCH'
  else:
    native_currency = currency
  validate_native_currency(native_currency)
  return native_currency


def from_native_currency(native_currency_str, current_datetime):
  validate_native_currency(native_currency_str)
  if native_currency_str == 'BSV':
    assert current_datetime >= BCHABC_BCHSV_FORK_TIME, current_datetime
    currency_str = 'BCHSV'
  elif native_currency_str == 'BCH':
    if current_datetime < BCHABC_BCHSV_FORK_TIME:
      currency_str = 'BCH'
    elif BCHABC_BCHSV_FORK_TIME <= current_datetime < BCHA_BCHN_FORK_TIME:
      currency_str = 'BCHABC'
    else:
      currency_str = 'BCHN'
  elif native_currency_str == 'BCHA':
    assert BCHA_BCHN_FORK_TIME <= current_datetime
    currency_str = 'BCHA'
  else:
    currency_str = native_currency_str
  return currency_str


class BybitCurrency(NativeCurrency):
  _exchange = "Bybit"

  @classmethod
  def FromStrCurrencyImpl(cls, currency_str, current_datetime):
    return cls(currency_str, to_native_currency(currency_str))

  @classmethod
  def FromStrNativeCurrencyImpl(cls, native_currency_str, current_datetime):
    return cls(from_native_currency(native_currency_str, current_datetime),
               native_currency_str)
